import { Response } from 'express';
import { AuthenticatedRequest } from '../types';
import ReportModel from '../models/reportModel';
import AnalysisModel from '../models/analysisModel';
import { ReportConfig } from '../config/analysisConfig';
import fs from 'fs';
import path from 'path';
import ejs from 'ejs';
import pdf from 'html-pdf';

// 生成报表
export const generateReport = async (req: AuthenticatedRequest, res: Response) => {
  try {
    const { reportId } = req.params;
    const report = await ReportModel.findById(reportId);

    if (!report) {
      return res.status(404).json({ message: '报表记录不存在' });
    }

    // 获取分析数据
    const analysis = await AnalysisModel.findOne({
      target: report.target,
      targetType: report.targetType,
      status: 'completed'
    });

    if (!analysis) {
      return res.status(400).json({ message: '分析数据尚未完成' });
    }

    // 设置导出状态
    report.exportHistory.push({
      timestamp: new Date(),
      format: report.format,
      status: 'processing'
    });

    await report.save();

    // 异步生成报表
    processReport(reportId, analysis);

    res.json({
      message: '报表生成任务已创建',
      reportId
    });
  } catch (error) {
    res.status(500).json({ message: '创建报表生成任务失败', error });
  }
};

// 获取报表状态
export const getReportStatus = async (req: AuthenticatedRequest, res: Response) => {
  try {
    const { reportId } = req.params;
    const report = await ReportModel.findById(reportId);

    if (!report) {
      return res.status(404).json({ message: '报表记录不存在' });
    }

    res.json({
      status: report.status,
      metadata: report.metadata,
      createdAt: report.createdAt,
      updatedAt: report.updatedAt,
      exportHistory: report.exportHistory
    });
  } catch (error) {
    res.status(500).json({ message: '获取报表状态失败', error });
  }
};

// 获取报表文件
export const getReportFile = async (req: AuthenticatedRequest, res: Response) => {
  try {
    const { reportId, historyId } = req.params;
    const report = await ReportModel.findById(reportId);

    if (!report) {
      return res.status(404).json({ message: '报表记录不存在' });
    }

    const exportRecord = report.exportHistory.find(
      h => h.timestamp.toString() === historyId
    );

    if (!exportRecord || !exportRecord.url) {
      return res.status(404).json({ message: '报表文件不存在' });
    }

    // 发送报表文件
    res.sendFile(path.resolve(exportRecord.url));
  } catch (error) {
    res.status(500).json({ message: '获取报表文件失败', error });
  }
};

// 内部辅助函数

// 异步处理报表生成
async function processReport(reportId: string, analysis: any) {
  try {
    const report = await ReportModel.findById(reportId);
    if (!report) return;

    const templatePath = ReportConfig.export.templates[report.type];
    if (!templatePath) {
      throw new Error('无效的报表模板');
    }

    // 渲染报表模板
    const html = await ejs.renderFile(templatePath, { analysis });

    // 导出文件路径
    const exportDir = path.join(__dirname, '..', 'exports');
    if (!fs.existsSync(exportDir)) {
      fs.mkdirSync(exportDir, { recursive: true });
    }

    const exportPath = path.join(exportDir, `${reportId}.${report.format}`);

    // 导出报表
    if (report.format === 'pdf') {
      await new Promise((resolve, reject) => {
        const pdfOptions: pdf.CreateOptions = {
        ...ReportConfig.export.pdf,
        format: ReportConfig.export.pdf.format as 'A4' | 'A3' | 'A5' | 'Legal' | 'Letter' | 'Tabloid',
        orientation: ReportConfig.export.pdf.orientation as 'portrait' | 'landscape'
      };
      pdf.create(html, pdfOptions).toFile(exportPath, (err, res) => {
          if (err) reject(err);
          else resolve(res);
        });
      });
    } else if (report.format === 'excel') {
      // TODO: 实现Excel导出
      throw new Error('Excel导出暂未实现');
    } else if (report.format === 'csv') {
      // TODO: 实现CSV导出
      throw new Error('CSV导出暂未实现');
    } else if (report.format === 'html') {
      fs.writeFileSync(exportPath, html);
    } else {
      throw new Error('无效的导出格式');
    }

    // 更新报表导出历史
    const exportRecord = report.exportHistory.find(
      h => h.timestamp.toString() === new Date().toString()
    );

    if (exportRecord) {
      exportRecord.status = 'completed';
      exportRecord.url = exportPath;
      await report.save();
    }

    console.log(`报表生成成功: ${exportPath}`);
  } catch (error) {
    console.error('报表生成失败:', error);

    const report = await ReportModel.findById(reportId);
    if (!report) return;

    const exportRecord = report.exportHistory.find(
      h => h.timestamp.toString() === new Date().toString()
    );

    if (exportRecord) {
      exportRecord.status = 'failed';
      exportRecord.error = error.message;
      await report.save();
    }
  }
}

// 创建报表
export const createReport = async (req: AuthenticatedRequest, res: Response) => {
  try {
    const { name, description, type, format, creator, filters, columns, charts, schedule, permissions } = req.body;

    // 创建报表记录
    const report = new ReportModel({
      name,
      description,
      type,
      format,
      creator,
      filters,
      columns,
      charts,
      schedule,
      status: 'draft',
      permissions
    });

    await report.save();

    res.json({
      message: '报表创建成功',
      reportId: report._id
    });
  } catch (error) {
    res.status(500).json({ message: '创建报表失败', error });
  }
};

// 更新报表
export const updateReport = async (req: AuthenticatedRequest, res: Response) => {
  try {
    const { reportId } = req.params;
    const { name, description, type, format, filters, columns, charts, schedule, permissions } = req.body;

    const report = await ReportModel.findById(reportId);

    if (!report) {
      return res.status(404).json({ message: '报表记录不存在' });
    }

    // 验证权限
    if (!report.permissions.edit.includes(req.user!.userId)) {
      return res.status(403).json({ message: '无权编辑此报表' });
    }

    // 更新报表数据
    report.name = name;
    report.description = description;
    report.type = type;
    report.format = format;
    report.filters = filters;
    report.columns = columns;
    report.charts = charts;
    report.schedule = schedule;
    report.permissions = permissions;

    await report.save();

    res.json({
      message: '报表更新成功',
      report
    });
  } catch (error) {
    res.status(500).json({ message: '更新报表失败', error });
  }
};

// 删除报表
export const deleteReport = async (req: AuthenticatedRequest, res: Response) => {
  try {
    const { reportId } = req.params;

    const report = await ReportModel.findById(reportId);

    if (!report) {
      return res.status(404).json({ message: '报表记录不存在' });
    }

    // 验证权限
    if (!report.permissions.delete.includes(req.user!.userId)) {
      return res.status(403).json({ message: '无权删除此报表' });
    }

    // 删除报表记录
    await report.deleteOne();

    res.json({ message: '报表删除成功' });
  } catch (error) {
    res.status(500).json({ message: '删除报表失败', error });
  }
};

// 获取报表列表
export const getReports = async (req: AuthenticatedRequest, res: Response) => {
  try {
    const reports = await ReportModel.find();

    res.json(reports);
  } catch (error) {
    res.status(500).json({ message: '获取报表列表失败', error });
  }
};

// 获取报表详情
export const getReportById = async (req: AuthenticatedRequest, res: Response) => {
  try {
    const { reportId } = req.params;
    const report = await ReportModel.findById(reportId);

    if (!report) {
      return res.status(404).json({ message: '报表记录不存在' });
    }

    res.json(report);
  } catch (error) {
    res.status(500).json({ message: '获取报表详情失败', error });
  }
};
